package com.leyou.search.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.JsonUtils;
import com.leyou.common.vo.PageResult;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.*;
import com.leyou.search.dto.GoodsDTO;
import com.leyou.search.dto.SearchRequest;
import com.leyou.search.pojo.Goods;
import com.leyou.search.repository.GoodsRepository;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilterBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SearchService {

    @Autowired
    private ItemClient itemClient;

    public Goods buildGoods(SpuDTO spuDTO) {
        //1.搜索字段，包含分类、品牌、标题等
        //1.1查询分类
        List<CategoryDTO> categoryDTOList = itemClient.queryCategoryByIds(spuDTO.getCategoryIds());
        String categoryName = categoryDTOList.stream().map(CategoryDTO::getName).collect(Collectors.joining());
        //1.2查询品牌
        BrandDTO brand = itemClient.queryBrandById(spuDTO.getBrandId());
        //1.3拼接
        String all = spuDTO.getName() + categoryName + brand.getName();
        //2.价格，spu下的所有sku价格
        List<SkuDTO> skuDTOList = itemClient.querySkuBySpuId(spuDTO.getId());
        List<Map<String, Object>> skuList = new ArrayList<>();
        for (SkuDTO sku : skuDTOList) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", sku.getId());
            map.put("price", sku.getPrice());
            map.put("title", sku.getTitle());
            map.put("image", StringUtils.substringBefore(sku.getImages(), ","));
            skuList.add(map);
        }
        //3.spu下的所有sku
        Set<Long> price = skuDTOList.stream().map(SkuDTO::getPrice).collect(Collectors.toSet());
        //4.规格参数，包含key和value
        Map<String, Object> specs = new HashMap<>();
        //4.1获取规格参数的key
        List<SpecParamDTO> specParams = itemClient.querySpecParams(null, spuDTO.getCid3(), true);
        //4.2获取规格参数的值
        SpuDetailDTO spuDetail = itemClient.querySpuDetailById(spuDTO.getId());
        //4.2.1通用规格参参数值
        Map<Long, Object> genericSpec = JsonUtils.toMap(spuDetail.getGenericSpec(), Long.class, Object.class);
        //4.2.2特有规格参数
        Map<Long, List<String>> specialSpec = JsonUtils.nativeRead(spuDetail.getSpecialSpec(), new TypeReference<Map<Long, List<String>>>() {
        });
        for (SpecParamDTO specParam : specParams) {
            //获取规格参数的名称
            String key = specParam.getName();
            Object value = null;
            //判断是否是通用规格
            if (specParam.getGeneric()) {
                value = genericSpec.get(specParam.getId());
            } else {
                value = specialSpec.get(specParam.getId());
            }
            //判断是否是数字类型
            if (specParam.getNumeric()) {
                // 是数字类型，分段
                value = chooseSegment(value, specParam);
            }
            //添加到specs
            specs.put(key, value);
        }

        //创建goods
        Goods goods = new Goods();
        goods.setSubTitle(spuDTO.getSubTitle());
        goods.setId(spuDTO.getId());
        goods.setCategoryId(spuDTO.getCid3());
        goods.setBrandId(spuDTO.getBrandId());
        goods.setCreateTime(spuDTO.getCreateTime().getTime());
        goods.setAll(all);
        goods.setPrice(price);
        goods.setSkus(JsonUtils.toString(skuList));
        goods.setSpecs(specs);
        return goods;
    }

    private String chooseSegment(Object value, SpecParamDTO p) {
        if (value == null || StringUtils.isBlank(value.toString())) {
            return "其它";
        }
        double val = parseDouble(value.toString());
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = parseDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = parseDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    private double parseDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return 0;
        }
    }

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private ElasticsearchTemplate esTemplate;

    public PageResult<GoodsDTO> search(SearchRequest request) {
        String key = request.getKey();
        //0.健壮性判断
        if (StringUtils.isBlank(key)) {
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        //1.创建原生搜索构建器
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        //2.组织条件
        //2.0source过滤，控制字段数量
        queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{"id", "subTitle", "skus"}, null));
        //2.1搜索条件
        QueryBuilder basicQueryBuilder = builderBasicQueryBuilder(request);
        queryBuilder.withQuery(basicQueryBuilder);
        //2.2分页条件
        Integer page = request.getPage() - 1;
        Integer size = request.getSize();
        queryBuilder.withPageable(PageRequest.of(page, size));

        //3.搜索结果
        AggregatedPage<Goods> goods = esTemplate.queryForPage(queryBuilder.build(), Goods.class);

        //4.解析结果
        long total = goods.getTotalElements();
        int totalPage = goods.getTotalPages();
        List<Goods> list = goods.getContent();
        //转换DTO
        List<GoodsDTO> dtoList = BeanHelper.copyWithCollection(list, GoodsDTO.class);

        //5.封装数据并返回
        return new PageResult<>(total, totalPage, dtoList);

    }

    private QueryBuilder builderBasicQueryBuilder(SearchRequest request) {
        //构建布尔查询
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        //构建基本的match查询
        queryBuilder.must(QueryBuilders.matchQuery("all", request.getKey()).operator(Operator.AND));
        //构建过滤条件
        Map<String, String> filters = request.getFilter();
        if (!CollectionUtils.isEmpty(filters)) {
            for (Map.Entry<String, String> entry : filters.entrySet()) {
                //获取过滤条件的key
                String key = entry.getKey();
                //规格参数的key要做前缀specs
                if ("分类".equals(key)) {
                    key = "categoryId";
                } else if ("品牌".equals(key)) {
                    key = "brandId";
                } else {
                    key = "specs." + key;
                }
                //value
                String value = entry.getValue();
                //添加过滤文件
                queryBuilder.filter(QueryBuilders.termQuery(key,value));
            }
        }
        return queryBuilder;
    }

    public Map<String, List<?>> queryFilterList(SearchRequest request) {
        Map<String, List<?>> filterList = new HashMap<>();
        //1.0创建原生搜索构建器
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        //2.0添加过滤条件
        //2.1搜索条件
        QueryBuilder basicQuery = builderBasicQueryBuilder(request);
        queryBuilder.withQuery(basicQuery);
        //2.2设置size为1，减少hits的数据
        queryBuilder.withPageable(PageRequest.of(0, 1));
        // 显示空的source
        queryBuilder.withSourceFilter(new FetchSourceFilterBuilder().build());
        //3.添加聚合条件
        //3.1分类的聚合
        String categoryAggName = "categoryAgg";
        queryBuilder.addAggregation(AggregationBuilders.terms(categoryAggName).field("categoryId"));
        //3.2品牌的聚合
        String brandAggName = "brandAgg";
        queryBuilder.addAggregation(AggregationBuilders.terms(brandAggName).field("brandId"));
        //4.查看聚合结果
        AggregatedPage<Goods> result = esTemplate.queryForPage(queryBuilder.build(), Goods.class);
        //5.解析聚合结果
        Aggregations aggs = result.getAggregations();
        //5.1解析分类的聚合
        List<Long> idList = handleCategoryAgg(filterList, aggs.get(categoryAggName));
        //5.2解析品牌的聚合
        handleBrandAgg(filterList, aggs.get(brandAggName));
        //5.3处理规格参数
        if (idList != null && idList.size() == 1) {
            handleSpecAgg(idList.get(0), basicQuery, filterList);
        }
        return filterList;
    }

    private void handleSpecAgg(Long cid, QueryBuilder basicQuery, Map<String, List<?>> filterList) {
        //1.根据分类id查询这个分类下需要搜索的规格参数
        List<SpecParamDTO> params = itemClient.querySpecParams(null, cid, true);
        //2.创建原生搜索构建器
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        //2.1搜索条件
        //2.1搜索条件
        queryBuilder.withQuery(basicQuery);
        //2.2设置size为1，减少hits的数据
        queryBuilder.withPageable(PageRequest.of(0, 1));
        // 显示空的source
        queryBuilder.withSourceFilter(new FetchSourceFilterBuilder().build());
        //3.对查询出的规格参数聚合
        for (SpecParamDTO param : params) {
            //取出param的名称，作为聚合的名称
            String name = param.getName();
            //添加聚合
            queryBuilder.addAggregation(AggregationBuilders.terms(name).field("specs." + name));
        }
        //4.查询数据
        AggregatedPage<Goods> result = esTemplate.queryForPage(queryBuilder.build(), Goods.class);

        //解析聚合结果，放到filterList中
        Aggregations aggs = result.getAggregations();
        //解析每个参数的聚合结果·
        for (SpecParamDTO param : params) {
            //取出param的名称，作为聚合的名称，取出聚合结果
            Terms terms = aggs.get(param.getName());
            //取出桶中的结果，直接作为待选项
            List<String> options = terms.getBuckets().stream()
                    .map(Terms.Bucket::getKeyAsString)
                    .filter(StringUtils::isNotBlank)
                    .collect(Collectors.toList());
            //放到map中去
            filterList.put(param.getName(), options);
        }
    }

    private void handleBrandAgg(Map<String, List<?>> filterList, Terms terms) {
        List<Long> idList = terms.getBuckets().stream()
                .map(bucket -> bucket.getKeyAsNumber().longValue())
                .collect(Collectors.toList());
        List<BrandDTO> options = itemClient.queryBrandByIds(idList);
        filterList.put("品牌", options);
    }

    private List<Long> handleCategoryAgg(Map<String, List<?>> filterList, Terms terms) {
        List<Long> idList = terms.getBuckets().stream()
                .map(bucket -> bucket.getKeyAsNumber().longValue())
                .collect(Collectors.toList());
        List<CategoryDTO> options = itemClient.queryCategoryByIds(idList);
        filterList.put("分类", options);
        return idList;
    }

    public void createIndex(Long id) {
        //查询spu
        SpuDTO spu = itemClient.querySpuById(id);
        //构建成goods对象
        Goods goods = buildGoods(spu);
        //保存到索引库
        goodsRepository.save(goods);
    }

    public void deleteById(Long id) {
        goodsRepository.deleteById(id);
    }
}
